/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "interface/network_port.h"

namespace dev {

std::string mac_addr_to_hex_string(const uint8_t* mac_addr, size_t len) {
    std::stringstream ss;
    for (size_t i = 0; i < len; ++i) {
        if (i > 0) {
            ss << ":";
        }
        ss << std::hex << std::uppercase << std::setfill('0') << std::setw(2)
           << static_cast<unsigned>(mac_addr[i]);
    }
    return ss.str();
}

bool NetworkPort::update_bdf_by_ncsi() {
    ncsi_bdf_info_t bdf = {};
    bool            ret = m_ncsi_over_mctp_huawei->get_bdf(DEFAULT_PACKAGE_ID, PortId, &bdf);
    if (!ret) {
        elog("Error: Failed to update BDF");
        return false;
    }
    char buffer[32];
    snprintf(buffer, sizeof(buffer), "%04x:%02x:%02x.%x", 0, bdf.bus, bdf.device, bdf.function);
    std::string bdf_str(buffer);

    BDF.set_value(bdf_str);
    return true;
}

bool NetworkPort::update_mac_addr_by_ncsi() {
    uint8_t mac_addr[6] = {};
    bool    ret = m_ncsi_over_mctp_huawei->get_mac_addr(DEFAULT_PACKAGE_ID, PortId, mac_addr, 6);
    if (!ret) {
        elog("Error: Failed to update MAC address");
        return false;
    }
    std::string mac_addr_str = mac_addr_to_hex_string(mac_addr, 6);
    MACAddress.set_value(mac_addr_str);
    return true;
}

bool NetworkPort::update_default_mac_addr_by_ncsi() {
    uint8_t mac_addr[6] = {};
    bool    ret =
        m_ncsi_over_mctp_huawei->get_default_mac_addr(DEFAULT_PACKAGE_ID, PortId, mac_addr, 6);
    if (!ret) {
        elog("Error: Failed to update default MAC address");
        return false;
    }
    std::string mac_addr_str = mac_addr_to_hex_string(mac_addr, 6);
    PermanentMACAddress.set_value(mac_addr_str);
    if ((MACAddress == "00:00:00:00:00:00") || (MACAddress == "N/A")) {
        MACAddress.set_value(mac_addr_str);
        ilog("update mac addr: ${mac_addr}", ("mac_addr", mac_addr_str));
    }
    return true;
}

void NetworkPort::start_ncsi_update_task_huawei(ncsi_over_mctp_hw_ptr ncsi_over_mctp,
                                                mc::milliseconds      interval) {
    m_ncsi_over_mctp_huawei = ncsi_over_mctp;
    m_ncsi_timer            = new mc::core::timer(this);
    
    // 重置计数器
    m_ncsi_timer_counter = 0;
    
    m_ncsi_timer->timeout.connect([this]() {
        // 增加计数器
        m_ncsi_timer_counter++;
        
        // 每10秒执行的任务（每次都执行）
        update_mac_addr_by_ncsi();
        
        // 每120秒执行的任务（每12次执行一次，即120秒/10秒=12）
        if (m_ncsi_timer_counter % 12 == 1) {  // 第1、13、25...次执行
            update_bdf_by_ncsi();
            update_default_mac_addr_by_ncsi();
            dlog("NetworkPort: executed 120s cycle tasks (count=${count})", ("count", m_ncsi_timer_counter));
        }
        
        dlog("NetworkPort: executed 10s cycle tasks (count=${count})", ("count", m_ncsi_timer_counter));
        
        // 防止计数器溢出，每120次重置（即1200秒后重置）
        if (m_ncsi_timer_counter >= 120) {
            m_ncsi_timer_counter = 0;
        }
    });
    
    m_ncsi_timer->set_single_shot(false);
    // 使用10秒作为基础间隔
    m_ncsi_timer->start(mc::milliseconds(10000));
}

void NetworkPort::stop_ncsi_update_task() {
    if (!m_ncsi_timer) {
        return;
    }
    m_ncsi_timer->stop();
    delete m_ncsi_timer;
    m_ncsi_timer = nullptr;
}

bool NetworkPort::SendNcsiTestPacket(uint8_t cmd_code, const std::string& req_data) {
    // 检查NCSI连接是否可用
    if (!m_ncsi_over_mctp_huawei) {
        elog("Error: NCSI over MCTP not initialized");
        return false;
    }

    try {
        // 发送NCSI测试包
        bool ret = m_ncsi_over_mctp_huawei->send_test_packet(DEFAULT_PACKAGE_ID, PortId, cmd_code,
                                                             req_data);
        if (!ret) {
            elog("Error: Failed to send NCSI test packet");
            return false;
        }

        return true;
    } catch (const std::exception& e) {
        elog("Error sending NCSI test packet: ${error}", ("error", e.what()));
        return false;
    }
}

void NetworkPort::update_mac_addr_by_smbus(uint8_t port_id) {
    // 使用静态变量缓存，减少频繁创建
    static mc::mutable_dict request_template{{"opcode", 0x404}};
    auto rsp = m_smbus_obj->send_request(request_template);
    if (rsp.empty()) {
        elog("Error: Failed to get mac address by smbus");
        return;
    }

    for (size_t i = 0; i < rsp.size(); i += 9) {
        uint8_t  port        = (rsp[i]);
        uint16_t PF_VF       = static_cast<uint16_t>((static_cast<uint16_t>(rsp[i + 1]) & 0xFF) |
                                                     (static_cast<uint16_t>(rsp[i + 2]) << 8));
        uint8_t  mac_addr[6] = {static_cast<uint8_t>(rsp[i + 3]), static_cast<uint8_t>(rsp[i + 4]),
                                static_cast<uint8_t>(rsp[i + 5]), static_cast<uint8_t>(rsp[i + 6]),
                                static_cast<uint8_t>(rsp[i + 7]), static_cast<uint8_t>(rsp[i + 8])};
        if (port == port_id) {
            std::string mac_addr_str = mac_addr_to_hex_string(mac_addr, 6);
            MACAddress.set_value(mac_addr_str);
            return;
        }
    }
}

void NetworkPort::start_smbus_update_task(smbus_obj_ptr smbus_obj, mc::milliseconds interval,
                                          uint8_t port_id) {
    if (!smbus_obj) {
        elog("Error: smbus_obj is not initialized");
        return;
    }
    m_smbus_obj   = smbus_obj;
    m_smbus_timer = new mc::core::timer(this);
    m_smbus_timer->timeout.connect([this, port_id]() {
        update_mac_addr_by_smbus(port_id);
    });
    m_smbus_timer->set_single_shot(false);
    m_smbus_timer->start(interval);
}

void NetworkPort::stop_smbus_update_task() {
    if (m_smbus_timer) {
        m_smbus_timer->stop();
        delete m_smbus_timer;
        m_smbus_timer = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::NetworkPort)